var _input_fieldId = '';
var _select_fieldId = '';
var _radio_fieldId = '';

/**
 * ajax 获取js去除时间戳.
 * ajax 获取的html代码片段，如果里面有js，会默认添加时间戳，无法命中服务器端缓存；通过修改jquery ajax 请求的配置，让其去掉时间戳
 * @param $
 */
(function($) {
	jQuery._evalUrl = function(url) {
		return jQuery.ajax({
			url : url,
			type : "GET",
			dataType : "script",
			async : false,
			global : false,
			"throws" : true,
			cache : true
		});
	};
})(jQuery); 

/**
 * ajax重写
 * url ：ajax请求的地址
 * params 请求的参数，如果参数不为空，请求方式为post
 * dataType  返回的参数 如：json html text
 * back_fun   回调函数
 * complete_fun    必定执行的参数
 * error_fun        发生错误的回调函数
 */
var _linwq_ajax = function(url, params, dataType, back_fun, complete_fun, error_fun) {
	var type = "get";
	if (params) {
		type = "post";
	}

	$.ajax({
		dataType : dataType, 
		type : type,
		url : url,
		data : params,
		async : false,
		timeout : 10000,
		//发送将将有报错的id的块的颜色清空
		beforeSend : function(xhr){
			/*$('body').loading({});*/
			if(_input_fieldId != ''){
				$('#' + _input_fieldId).css('border-color', '');
			}
			if(_select_fieldId != ''){
				$('#' + _select_fieldId).next().children("button").css('border-color', '');
				$('#' + _select_fieldId).css('border-color', '');
			}
			if(_radio_fieldId != ''){
				$('[id=' + _radio_fieldId + ']').each(function(){
					$(this).parent().css('border-color', '');
				});
			}
			_input_fieldId = '';
			_select_fieldId = '';
			_radio_fieldId = '';
		},
		success : function(msg) {
			/*$('body').loading('stop');*/
			back_fun(msg);
		},
		complete : function() {
			if (complete_fun) {
				complete_fun();
			}
		},
		error : function(xhr, type , ex) {
			console.log(xhr);
			console.log(type);
			console.log(ex);
			debugger;
			/*$('body').loading('stop');*/
			if (error_fun) {
				error_fun(xhr, type);
			}else{
				// 登录超时处理
				if (xhr.status == 1002) {
					var curWwwPath = window.document.location.href;
					var pathName = window.document.location.pathname;
					var pos = curWwwPath.indexOf(pathName);
					var localhostPaht = curWwwPath.substring(0, pos);
					var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
					window.top.location.replace(localhostPaht + projectName);
				}
				
				var jsonStr = xhr.responseText.split('<script')[0];
				var jsonObj = jQuery.parseJSON(jsonStr)
				var message = jsonObj.message;
				if(message == ''){
					message = jsonObj.stackTrace;
				}
				parent.layer.alert(message, {
					title: '发生错误',
				    icon: 2,
				    skin: 'layer-ext-moon'
				},function(index){
					parent.layer.close(index);
					var fieldId = jsonObj.fieldId;
					if( fieldId != ''){
						var obj = $('#' + fieldId);
						
						// Amaze UI 处理方式，其他Css的时候需要修改以下代码。
						// 下拉选择框
						if(obj[0].tagName=='SELECT'){
							_select_fieldId = fieldId;
							// 普通select框
							obj.focus().css('border-color', 'red');
							// Amaze UI选择框
							obj.next().children("button").css('border-color', 'red');
						}else	if(obj[0].tagName=='INPUT'){
							// 普通输入框、日期输入框、密码
							if(obj[0].type == 'text' || obj[0].type == 'date' || obj[0].type == 'password'){
								_input_fieldId = fieldId;
								obj.focus().css('border-color', 'red');
							}
							// radio button
							else if(obj[0].type == 'radio'){
									_radio_fieldId = fieldId;
									$('[id=' + fieldId + ']').each(function(){
										$(this).parent().css('border-color', 'red');
									}
								);
							}
						}
					}
				});
			}
		}
	});
};


/**
 * 将传的进来的字符串的空格去掉
 */
var _linwq_trim=function(a){
	if(!a){
		return "";
	}
	return a.replace(/\s/g, "");
}

/**
 * 通过id  
 * 去改变border—color的颜色
 */
var _linwq_borderColor=function(id,color){
	if(!color){
		color='';
	}
	$("#"+id).css('border-color', color);
}


/**
 * 询问弹出框
 * msg询问内容
 * btn1第一个按钮 如：确认
 * btn2第二个按钮 如：取消
 * confirm  第一个按钮的回调函数
 * confirm  第二个按钮的回调函数
 */
var _linwq_confirm=function(msg,btn1,btn2,confirm,cancel){
	layer.confirm(msg, {
		  btn: [btn1,btn2] //按钮
		}, function(){
			if(confirm){
				confirm();
			}
			/*layer.msg('操作成功！', {icon: 1});*/
		}, function(){
			if(cancel){
				cancel();
			}
		  /*layer.msg('也可以这样', {
			time: 20000, //20s后自动关闭
			btn: ['明白了', '知道了']
		  });*/
	});
}


var _linwq_unid=function(size1,number1){
	var uuid = "";
	var size = 4;
	var number = 10;
	if(size1){
		size=size1;
	}
	if(number1){
		number=number1;
	}
	for(var i=0;i<size;i++){
		uuid+=_linwq_uuSize(number);
	}
	return uuid;
}
var _linwq_uuSize=function(size){
	if(size>36||size<1){
		return null;
	}else{
		return (Math.random()*size|0).toString(size);
	}
}

var _linwq_mqttws31=function(lName,lHost,lPort){
	var host=lHost?lHost:"192.168.1.221";
	var port=lPort?lPort:61614;
	var clientID=_linwq_unid(8, 36);
	var destination=lName?lName:"linwq";
	
	
	window.client=new Messaging.Client(host,Number(port),clientID);
	console.info(client);
	client.onMessageArrived=function(e){
		alert(e.payloadString);
		console.info(e.payloadString);
	}; 
	client.onConnectionLost=function(e){
		console.info("断开连接");
	};
	client.connect({
		onSuccess:function(){
			client.subscribe(destination);
			console.info("连接成功");
		},
		onFailure:function(){
			console.info("连接失败");
		}
	}); 
}


var _linwq_subString=function (str,newlength){
	var chineseRegex=/[^\x00-\xff]/g;
	var newStr = "";
	for(var i=0;i<str.length;i++){
		if(newStr.replace(chineseRegex, "**").length>newlength){
			newStr +="...";
			return newStr;
		}else{
			newStr += str.charAt(i);
		}
	}
}
/*
var gage = $.extend({}, gage);
*
 * 获得项目根路径
 * 
 *
gage.context = function() {
	var curWwwPath = window.document.location.href;
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	var localhostPaht = curWwwPath.substring(0, pos);
	var projectName = pathName
			.substring(0, pathName.substr(1).indexOf('/') + 1);
	return (localhostPaht + projectName);
};
//datagrid合并单元格
$.extend($.fn.datagrid.methods, {
	autoMergeCells : function(jq, fields) {
		return jq.each(function() {
			var target = $(this);
			if (!fields) {
				fields = target.datagrid("getColumnFields");
			}
			var rows = target.datagrid("getRows");
			var i = 0, j = 0, temp = {};
			for (i; i < rows.length; i++) {
				var row = rows[i];
				j = 0;
				for (j; j < fields.length; j++) {
					var field = fields[j];
					var tf = temp[field];
					if (!tf) {
						tf = temp[field] = {};
						tf[row[field]] = [ i ];
					} else {
						var tfv = tf[row[field]];
						if (tfv) {
							tfv.push(i);
						} else {
							tfv = tf[row[field]] = [ i ];
						}
					}
				}
			}
			$.each(temp, function(field, colunm) {
				$.each(colunm, function() {
					var group = this;
					if (group.length > 1) {
						var before, after, megerIndex = group[0];
						for ( var i = 0; i < group.length; i++) {
							before = group[i];
							after = group[i + 1];
							if (after && (after - before) == 1) {
								continue;
							}
							var rowspan = before - megerIndex + 1;
							if (rowspan > 1) {
								target.datagrid('mergeCells', {
									index : megerIndex,
									field : field,
									rowspan : rowspan
								});
							}
							if (after && (after - before) != 1) {
								megerIndex = after;
							}
						}
					}
				});
			});
		});
	}
});*/